package com.gopay.bis.cmbc.ebank.operation;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.domain.bank.cmbc.ebank.CmbcMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.ICertHelper;

/**
 * 解析民生B2C对账交易返回XML
 * 
 * @CmbcParseMessage.java
 */
public class CmbcParseMessage {

	/** 验签实现类 */
	private ICertHelper cmbcB2cCerthelper;

	/**
	 * @param receivedMsgData
	 * @return
	 * @throws GopayException
	 * @throws DocumentException
	 * @throws UnsupportedEncodingException
	 */
	public CmbcMessage parseCmbcMessage(Object receivedMsgData,CmbcMessage cmbcMessage)
			throws GopayException, DocumentException,
			UnsupportedEncodingException {
		String reciverDate = null;
		if (receivedMsgData instanceof byte[]) {
			reciverDate = URLDecoder.decode(
					new String((byte[]) receivedMsgData), "UTF-8");
		} else if (receivedMsgData instanceof String) {
			reciverDate = (String) receivedMsgData;
		}
		Document document = null;
		document = DocumentHelper.parseText(URLDecoder.decode(new String(
				reciverDate.getBytes())));
		Element rootEle = document.getRootElement();
		Element bodyEle = rootEle.element("body");
		Element divEle = bodyEle.element("div");
		// div 中是密文，解析出来放在CMBCMessage对象中
		String signNatrue = new String(divEle.getTextTrim());
		String plainNatrue = null;
		CmbcMessage resMsg = new CmbcMessage();
		if (signNatrue.startsWith("报文数据")) {
			resMsg.setRemark(signNatrue);
		} else {
			resMsg.setSignMessage(signNatrue);
			resMsg.setOutStlmCd(BankConstants.BANK_LOGO_CMBC);
			resMsg.setPrivateKeyPath(cmbcMessage.getPrivateKeyPath());
			resMsg.setPrivateKeyPath2nd(cmbcMessage.getPrivateKeyPath2nd());
			resMsg.setPublicKeyPath(cmbcMessage.getPublicKeyPath());
			resMsg.setPrivatePwd(cmbcMessage.getPrivatePwd());
			resMsg.setPrivatePwd2nd(cmbcMessage.getPrivatePwd2nd());
			plainNatrue = (String) cmbcB2cCerthelper.verify(resMsg);
			String[] tempStr = plainNatrue.split("\\|");
			System.out.println(plainNatrue);
			if (tempStr != null && tempStr.length >= 4) {
				resMsg.setOrderNo(tempStr[0] == null ? "" : tempStr[0]);
				if (tempStr[1] != null) {
					resMsg.setAmount(new BigDecimal(tempStr[1]));
				}
				resMsg.setOrderAmt(tempStr[1] == null ? "" : tempStr[1]);
				resMsg.setOrderStatus(tempStr[2] == null ? "" : tempStr[2]);
				resMsg.setRemark(tempStr[3] == null ? "" : tempStr[3]);
			}

		}
		return resMsg;
	}

	public ICertHelper getCmbcB2cCerthelper() {
		return cmbcB2cCerthelper;
	}

	public void setCmbcB2cCerthelper(ICertHelper cmbcB2cCerthelper) {
		this.cmbcB2cCerthelper = cmbcB2cCerthelper;
	}

}
